package cn.genmer.test.security.netty.nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @program:  读取数据，打印在控制台
 * @description:
 * @author: Genmer
 * @create: 2021-09-04 22:15
 **/
public class Channel2 {
    public static void main(String[] args) throws IOException {


        File file = new File("/Users/genmersmbp/Documents/Codes/tmp/channel1.txt");
        // 创建一个输出流
        FileInputStream fileInputStream = new FileInputStream(file);

        // 获得channel - 如果channel实例为空，会实例化一个FileChannelImpl - 方法内部一个synchronized的大括号
        FileChannel channel = fileInputStream.getChannel();

        // 创建缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate((int) file.length());

        // 从channel读取数据到buffer - 结果为字节，需要转换
        channel.read(byteBuffer);
        // 字节转换为字符串


        System.out.println(new String(byteBuffer.array()));

        fileInputStream.close();
    }
}
